package pojo;

import java.io.File;
import java.io.FileInputStream;
import java.io.ObjectInputStream;
import java.io.Serializable;
import java.time.LocalDate;
import java.util.Iterator;
import java.util.List;

public class Employee implements Serializable {
    private int employeeId;
    private String name;
    private String sex;
    private int age;
    private double salary;
    private Department department;
    private LocalDate entryDate;

    public int getEmployeeId() {
        return employeeId;
    }

    public String getName() {
        return name;
    }

    public String getSex() {
        return sex;
    }

    public int getAge() {
        return age;
    }

    public double getSalary() {
        return salary;
    }

    public Department getDepartment() {
        return department;
    }

    public LocalDate getEntryDate() {
        return entryDate;
    }

    public void update(String name,String sex,int age,double salary,Department department){
        this.name = name;
        this.sex = sex;
        this.age = age;
        this.salary = salary;
        this.department = department;
    }

    public void updateDepartment(Department department){
        this.department = department;
    }

    public Employee() {
    }

    public Employee(String name, String sex, int age, double salary, Department department) {
        this.employeeId = getNewId();
        this.name = name;
        this.sex = sex;
        this.age = age;
        this.salary = salary;
        this.department = department;
        this.entryDate = LocalDate.now();
    }

    private int getNewId(){
        int id = 10000;
        File loadFile = new File("saveData\\employeeData");
        if(!loadFile.exists()){
            return id;
        } else{
            try{
                ObjectInputStream ois = new ObjectInputStream(new FileInputStream(loadFile));
                List<Employee> list = (List<Employee>) ois.readObject();
                Iterator iterator = list.iterator();
                while(iterator.hasNext()){
                    Employee employee = (Employee) iterator.next();
                    if(id != employee.getEmployeeId()){
                        return id;
                    }
                    id += 1;
                }
                return id;
            } catch(Exception e){
                throw new RuntimeException(e);
            }
        }
    }
}
